package se

import (
	"gitee.com/xuender/oils/logs"
	"gitee.com/xuender/oils/sets"
	"gitee.com/xuender/se/pb"
)

// Search 搜索.
func (p *Service) Search(wordses []string) []*pb.File {
	wordSet := sets.NewUint32s()

	for _, words := range wordses {
		logs.Debug("搜索词组:", words)

		if id := p.ws.Word(words, false); id > 0 {
			logs.Debug("存在词组", id, words)
			wordSet.Add(id)

			continue
		}

		ws := Split(words)
		ids := p.ws.wordIDs(ws)
		logs.Debug("ids:", ws, ids)
		// ID和词数量一致，可能是词组
		if len(ids) == len(ws) {
			logs.Debug("可能是词组")
			// 根据词查找文件，根据文件ID和词组生成词组,返回关联的文件ID
			wordSet.Add(p.FindWords(p.fs.FileByWord(ids), words)...)
		}

		wordSet.Add(ids...)
	}

	logs.Debug("ids:", wordSet)
	words := wordSet.Slice()
	fileIDs := sets.NewUint32s(p.fs.FileByWord(words)...)
	ids := fileIDs.Slice()
	logs.Debug("size:", len(ids))

	if len(ids) < int(p.ctx.Offset) {
		return []*pb.File{}
	}

	limit := int(p.ctx.Offset + p.ctx.Limit)
	if len(ids) < limit {
		limit = len(ids)
	}

	ids = ids[p.ctx.Offset:limit]
	files := p.fs.Files(ids)
	findWords := p.ws.wordStrings(wordSet)

	for _, f := range files {
		p.fs.Hit(f, findWords)
	}

	return files
}
